from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.dao.ocr_config_dao import OcrConfigDao
from module_admin.entity.vo.ocr_config_vo import DeleteOcrConfigModel, OcrConfigModel, OcrConfigPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class OcrConfigService:
    """
    OCR配置模块服务层
    """

    @classmethod
    async def get_OcrConfig_list_services(
        cls, query_db: AsyncSession, query_object: OcrConfigPageQueryModel, is_page: bool = False
    ):
        """
        获取OCR配置列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: OCR配置列表信息对象
        """
        OcrConfig_list_result = await OcrConfigDao.get_OcrConfig_list(query_db, query_object, is_page)

        return OcrConfig_list_result

    # 自增ID无需检查唯一性，已移除check_id_unique_services方法


    @classmethod
    async def add_OcrConfig_services(cls, query_db: AsyncSession, page_object: OcrConfigModel):
        """
        新增OCR配置信息service

        :param query_db: orm对象
        :param page_object: 新增OCR配置对象
        :return: 新增OCR配置校验结果
        """
        # 自增ID字段，新增时不需要传入ID
        try:
            await OcrConfigDao.add_OcrConfig_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_OcrConfig_services(cls, query_db: AsyncSession, page_object: OcrConfigModel):
        """
        编辑OCR配置信息service

        :param query_db: orm对象
        :param page_object: 编辑OCR配置对象
        :return: 编辑OCR配置校验结果
        """
        if page_object.id is None:
            raise ServiceException(message='修改OCR配置失败，ID不能为空')
        
        edit_OcrConfig = page_object.model_dump(exclude_unset=True, exclude={})
        OcrConfig_info = await cls.OcrConfig_detail_services(query_db, page_object.id)
        if OcrConfig_info.id:
            try:
                await OcrConfigDao.edit_OcrConfig_dao(query_db, edit_OcrConfig)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='OCR配置不存在')

    @classmethod
    async def delete_OcrConfig_services(cls, query_db: AsyncSession, page_object: DeleteOcrConfigModel):
        """
        删除OCR配置信息service

        :param query_db: orm对象
        :param page_object: 删除OCR配置对象
        :return: 删除OCR配置校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await OcrConfigDao.delete_OcrConfig_dao(query_db, OcrConfigModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入ID为空')

    @classmethod
    async def OcrConfig_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取OCR配置详细信息service

        :param query_db: orm对象
        :param id: ID
        :return: ID对应的信息
        """
        OcrConfig = await OcrConfigDao.get_OcrConfig_detail_by_id(query_db, id=id)
        if OcrConfig:
            result = OcrConfigModel(**CamelCaseUtil.transform_result(OcrConfig))
        else:
            result = OcrConfigModel(**dict())

        return result

    @staticmethod
    async def export_OcrConfig_list_services(OcrConfig_list: List):
        """
        导出OCR配置信息service

        :param OcrConfig_list: OCR配置信息列表
        :return: OCR配置信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': 'ID',
            'confKey': '配置key',
            'confValue': '配置值',
            'confRemark': '配置描述',
        }
        binary_data = ExcelUtil.export_list2excel(OcrConfig_list, mapping_dict)

        return binary_data
